package com.scud.system.utils;

import com.scud.model.system.pojo.Permission;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class TreeUtil {
    /**
     * 使用递归方法建菜单
     *
     * @param permissions
     * @return
     */
    public static List<Permission> buildTree(List<Permission> permissions) {
        List<Permission> trees = new ArrayList<>();
        for (Permission p : permissions) {
            if (p.getParentId() == 0) {
                trees.add(findChildren(p, permissions));
            }
        }
        return trees;
    }

    /**
     * 递归查找子节点
     *
     * @param permissions
     * @return
     */
    public static Permission findChildren(Permission p, List<Permission> permissions) {
        p.setChildren(new ArrayList<>());
        for (Permission it : permissions) {
            if (Objects.equals(p.getId(), it.getParentId())) {
                p.getChildren().add(findChildren(it, permissions));
            }
        }
        return p;
    }
}
